<template>
  <CollapseContainer title="修改密码" :canExpan="false">
    <div class="py-8 bg-white flex flex-col justify-center">
      <a-form
        :model="formData"
        ref="formRef"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="当前密码" name="passwordOld">
          <a-input v-model:value="formData.passwordOld" />
        </a-form-item>
        <a-form-item label="新密码" name="passwordNew">
          <a-input v-model:value="formData.passwordNew" />
        </a-form-item>
        <a-form-item label="确认密码" name="confirmPassword">
          <a-input v-model:value="formData.confirmPassword" />
        </a-form-item>
      </a-form>
      <div class="flex justify-center">
        <a-button class="!ml-4" type="primary" @click="handleSubmit"> 确认 </a-button>
      </div>
    </div>
  </CollapseContainer>
</template>
<script lang="ts">
export default {
  name: 'ChangePassword',
};
</script>
<script setup lang="ts">
import { ref } from 'vue';
import { message, FormInstance } from 'ant-design-vue';
import { CollapseContainer } from '/@/components/Container';
import { modifyPwd } from '/@/api/sys/user';
import { useGo } from '/@/hooks/web/usePage';
const go = useGo();
const formRef = ref<FormInstance>();
const formData = ref({
  passwordOld: '',
  passwordNew: '',
  confirmPassword: '',
});

let validateConfirmPassword = async (_rule: Object, value: string) => {
  if (value === '') {
    return Promise.reject('请再次输入密码');
  } else if (value != formData.value.passwordNew) {
    return Promise.reject('两次输入的密码不一致!');
  } else {
    return Promise.resolve();
  }
};

const rules = {
  passwordOld: [{ required: true, trigger: 'change', message: '请输入当前密码' }],
  passwordNew: [{ required: true, trigger: 'change', message: '请输入新密码' }],
  confirmPassword: [
    {
      required: true,
      trigger: 'change',
      validator: validateConfirmPassword,
    },
  ],
};

const confirmLoading = ref<boolean>(false);
const handleSubmit = async () => {
  try {
    confirmLoading.value = true;
    await formRef.value?.validate();
    const { passwordOld, passwordNew, confirmPassword } = formData.value;
    await modifyPwd({
      passwordOld: passwordOld,
      passwordNew: passwordNew,
      confirmPassword: confirmPassword,
    });
    message.success('密码修改成功,请重新登录');
    go('/login');
  } finally {
    confirmLoading.value = false;
  }
};
</script>
